export const todos = (state = [], action) => {
  switch (action.type) {
    // type=add_todo, payload={id, text}
    case 'add_todo':
      return [...state, { ...action.payload, completed: false }]
    // type=remove_todo, payload=id
    case 'remove_todo':
      return state.filter((todo) => todo.id !== action.payload)
    // type=toggle_todo, payload=id
    case 'toggle_todo':
      const todoIndex = state.findIndex((todo) => todo.id === action.payload)
      const newTodo = {
        ...state[todoIndex],
        completed: !state[todoIndex].completed,
      }
      return [
        ...state.slice(0, todoIndex),
        newTodo,
        ...state.slice(todoIndex + 1),
      ]
    // type=filter
    default:
      return state
  }
}

export function getVisibleTodos(todos, filter) {
  // selector
  switch (filter) {
    case 'all':
      return todos
    case 'active':
      return todos.filter((todo) => !todo.completed)
    case 'completed':
      return todos.filter((todo) => todo.completed)
    default:
      throw new Error('无效的filter值：'+filter)
  }
}